"use client";

import { useState, useEffect } from "react";
import { Host, getHosts, createHost, updateHost } from "@/lib/api";
import { PlusIcon, SaveIcon, XIcon } from "lucide-react";
import { DataTable } from "@/components/ui/data-table/data-table";
import { hostColumns } from "./columns";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import React from "react";

export default function HostsPage() {
  const [hosts, setHosts] = useState<Host[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [isDialogOpen, setIsDialogOpen] = useState(false);
  const [searchTerm, setSearchTerm] = useState("");
  const [formData, setFormData] = useState({
    hostname: "",
    ip_address: "",
    status: "active"
  });
  const [editingHost, setEditingHost] = useState<Host | null>(null);

  // Fetch hosts from backend
  const fetchHosts = async () => {
    try {
      setLoading(true);
      const data = await getHosts({ search: searchTerm });
      setHosts(data.results);
      setError(null);
    } catch (err) {
      setError("Failed to fetch hosts");
      console.error(err);
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchHosts();
  }, [searchTerm]);

  const handleCreateHost = async (event: React.FormEvent) => {
    event.preventDefault();
    try {
      // In a real implementation, you would collect form data and call createHost
      // For now, we'll just close the dialog
      setIsDialogOpen(false);
      // Reset form
      setFormData({
        hostname: "",
        ip_address: "",
        status: "active"
      });
      setEditingHost(null);
      // Refresh the host list
      fetchHosts();
    } catch (err) {
      console.error("Failed to create host", err);
    }
  };

  const handleEditHost = (host: Host) => {
    setEditingHost(host);
    setFormData({
      hostname: host.hostname,
      ip_address: host.ip_address,
      status: host.status
    });
    setIsDialogOpen(true);
  };

  const handleUpdateHost = async (event: React.FormEvent) => {
    event.preventDefault();
    if (!editingHost) return;
    
    try {
      await updateHost(editingHost.id, {
        hostname: formData.hostname,
        ip_address: formData.ip_address,
        status: formData.status
      });
      
      setIsDialogOpen(false);
      setEditingHost(null);
      setFormData({
        hostname: "",
        ip_address: "",
        status: "active"
      });
      fetchHosts();
    } catch (err) {
      console.error("Failed to update host", err);
    }
  };

  const handleInputChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const { id, value } = e.target;
    setFormData(prev => ({
      ...prev,
      [id]: value
    }));
  };

  const handleSelectChange = (value: string, name: string) => {
    setFormData(prev => ({
      ...prev,
      [name]: value
    }));
  };

  const handleSubmit = editingHost ? handleUpdateHost : handleCreateHost;

  const columns = hostColumns(handleEditHost);

  if (loading) {
    return (
      <div className="container mx-auto py-10">
        <Card>
          <CardHeader>
            <div className="flex justify-between items-center">
              <div>
                <CardTitle className="text-3xl font-bold">Hosts</CardTitle>
                <CardDescription>Loading hosts...</CardDescription>
              </div>
            </div>
          </CardHeader>
          <CardContent>
            <div className="space-y-2">
              {[1, 2, 3, 4, 5].map((item) => (
                <div key={item} className="h-10 bg-gray-200 rounded animate-pulse"></div>
              ))}
            </div>
          </CardContent>
        </Card>
      </div>
    );
  }

  if (error) {
    return (
      <div className="container mx-auto py-10">
        <Card>
          <CardHeader>
            <CardTitle className="text-3xl font-bold">Hosts</CardTitle>
            <CardDescription className="text-red-500">{error}</CardDescription>
          </CardHeader>
          <CardContent>
            <p className="text-muted-foreground">Failed to load hosts. Please try again later.</p>
          </CardContent>
        </Card>
      </div>
    );
  }

  return (
    <div className="container mx-auto py-10">
      <Card>
        <CardHeader>
          <div className="flex justify-between items-center">
            <div>
              <CardTitle className="text-3xl font-bold">Hosts</CardTitle>
              <CardDescription>Manage your infrastructure hosts</CardDescription>
            </div>
            <Button onClick={() => setIsDialogOpen(true)} className="bg-primary hover:bg-primary/90">
              <PlusIcon />
              Add New Host
            </Button>
          </div>
        </CardHeader>
        <CardContent>
          <DataTable 
            columns={columns} 
            data={hosts} 
            searchField="hostname"
            onSearch={(value) => setSearchTerm(value)}
          />
        </CardContent>
      </Card>
      
      {/* Add/Edit Host Dialog */}
      {isDialogOpen && (
        <div className="fixed inset-0 bg-black/50 flex items-center justify-center p-4 z-50">
          <div className="bg-background rounded-lg border p-6 w-full max-w-md">
            <div className="space-y-4">
              <div>
                <h3 className="text-lg font-semibold">
                  {editingHost ? "Edit Host" : "Add New Host"}
                </h3>
                <p className="text-sm text-muted-foreground">
                  {editingHost 
                    ? "Update the details below to edit the host." 
                    : "Fill in the details below to add a new host to the system."}
                </p>
              </div>
              <form className="space-y-4" onSubmit={handleSubmit}>
                <div className="space-y-2">
                  <Label htmlFor="hostname">Hostname</Label>
                  <Input 
                    id="hostname" 
                    placeholder="Enter hostname" 
                    value={formData.hostname}
                    onChange={handleInputChange}
                    required
                  />
                </div>
                <div className="space-y-2">
                  <Label htmlFor="ip_address">IP Address</Label>
                  <Input 
                    id="ip_address" 
                    placeholder="Enter IP address" 
                    value={formData.ip_address}
                    onChange={handleInputChange}
                    required
                  />
                </div>
                <div className="space-y-2">
                  <Label htmlFor="status">Status</Label>
                  <Select 
                    value={formData.status} 
                    onValueChange={(value) => handleSelectChange(value, "status")}
                  >
                    <SelectTrigger>
                      <SelectValue placeholder="Select status" />
                    </SelectTrigger>
                    <SelectContent>
                      <SelectItem value="active">Active</SelectItem>
                      <SelectItem value="maintenance">Maintenance</SelectItem>
                      <SelectItem value="retired">Retired</SelectItem>
                    </SelectContent>
                  </Select>
                </div>
                <div className="flex justify-end space-x-2">
                  <Button type="button" variant="outline" onClick={() => {
                    setIsDialogOpen(false);
                    setEditingHost(null);
                  }}>
                    <XIcon />
                    Cancel
                  </Button>
                  <Button type="submit" className="bg-primary hover:bg-primary/90">
                    {editingHost ? (
                      <>
                        <SaveIcon />
                        Update Host
                      </>
                    ) : (
                      <>
                        <PlusIcon />
                        Add Host
                      </>
                    )}
                  </Button>
                </div>
              </form>
            </div>
          </div>
        </div>
      )}
    </div>
  );
}
